﻿//////////////////////////////////////////
/// 
/// Substitution for System.Net.Mail.MailAddress
/// Represent an Email Address
/// By marstone@marstone.net, 2008/12/02
/// 
//////////////////////////////////////////

using System;
using System.Text.RegularExpressions;

namespace Studio.Network.Mail
{
    public class EmailAddress
    {

        public static string EMAIL_PATTERN = "^[\\w|-|\\.]+@([a-zA-Z_0-9]+?\\.)+[a-zA-Z]{2,4}$";

        public static bool Validate(string address)
        {
            Regex regexEmail = new Regex(EMAIL_PATTERN);
            return regexEmail.IsMatch(address);
        }

        string _address;

        public string Address
        {
            get { return _address; }
            set { _address = value; }
        }
        string _displayName;

        public string DisplayName
        {
            get { return _displayName; }
            set { _displayName = value; }
        }

        public EmailAddress(string address)
        {
            if (true == EmailAddress.Validate(address))
                this._address = address;
            else
            { 
                string Pattern = EmailAddress.EMAIL_PATTERN;
                if(Pattern.StartsWith("^[")) Pattern.Remove(0, 2);
                if(Pattern.EndsWith("$")) Pattern.Substring(0, Pattern.Length - 1);
                string BracketPattern = string.Format("^[<{0}>$", Pattern);
                Regex regexEmail = new Regex(BracketPattern);
                Match match = Regex.Match(address, BracketPattern);
                // Parse Failed.
                if (match.Length <= 0)
                    throw new ArgumentException();

                this._address = match.Value.Trim("<>".ToCharArray());
                this._displayName = address.Replace(match.Value, "").Trim(" \r\n\t".ToCharArray());
            }
        }

        public static EmailAddress ParseEmailAddress(string address)
        {
            try
            {
                return new EmailAddress(address);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return null;
            }
        }

        public EmailAddress(string address, string displayName)
        {
            if (false == EmailAddress.Validate(address))
                throw new ArgumentException();
            this._address = address;
            this._displayName = displayName;
        }

        public override string ToString()
        {
            return string.Format("{0}<{1}>", this._displayName, this._address);
        }
    }
}
